<template>
  <view class="home-container">
    <!-- 页面加载状态 -->
    <PageLoading :show="pageLoading" :primary-color="primaryColor" loading-text="加载中..." />
    
    <!-- 页面主要内容 -->
    <view class="page-content" v-show="shouldShowContent">
    <!-- 弹窗广告 -->
    <view class="popup-overlay" v-if="programConfig.showPopup && showPopupAd && currentPopupAd" @click="closePopupAd">
      <view class="popup-content" @click.stop>
        <view class="popup-close" @click="closePopupAd">
          <text class="close-icon">✕</text>
        </view>
        <image class="popup-image" :src="currentPopupAd.image" mode="aspectFill"></image>
        <view class="popup-info">
          <text class="popup-title" :style="{color: themeColorStyles.primaryColor}">{{ currentPopupAd.title }}</text>
          <text class="popup-subtitle" v-if="currentPopupAd.remark">{{ currentPopupAd.remark }}</text>
          <view class="popup-button" :style="{background: `linear-gradient(135deg, ${themeColorStyles.primaryColor} 0%, ${themeColorStyles.primaryColorLight} 100%)`, boxShadow: `0 8rpx 25rpx ${themeColorStyles.primaryColorShadow}`}" @click="handlePopupAction">
            <text class="button-text">查看详细</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 轮播图 -->
    <view class="banner-section animate-fade-in" v-if="programConfig.showBanner && bannerList && bannerList.length > 0">
      <view class="banner-container">
        <swiper class="banner-swiper" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="500" indicator-color="rgba(255,255,255,0.5)" :indicator-active-color="primaryColor">
          <swiper-item v-for="(item, index) in bannerList" :key="index">
            <image class="banner-image" :src="item.image" mode="aspectFill" @click="clickBanner(item)"></image>
          </swiper-item>
        </swiper>
      </view>
    </view>

    <!-- 公告滚动 -->
    <view class="notice-section animate-slide-up" :style="{animationDelay: '0.02s'}" v-if="programConfig.showNotice && noticeList && noticeList.length > 0">
      <view class="notice-icon animate-bounce">
        <text class="notice-emoji">📢</text>
      </view>
      <swiper class="notice-swiper" :vertical="false" :autoplay="true" :interval="4000" :duration="500" :display-multiple-items="1">
        <swiper-item v-for="(notice, index) in noticeList" :key="index">
          <text class="notice-text" @click="clickNotice(notice)">{{ notice.displayText || notice.content }}</text>
        </swiper-item>
      </swiper>
    </view>

    <!-- 菜单导航 -->
    <view class="menu-section animate-slide-up" :style="{animationDelay: '0.1s', '--primary-color': primaryColor, boxShadow: `0 8rpx 32rpx ${themeColorStyles.primaryColorShadow}`, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}" v-if="programConfig.showNavButtons">
      <view class="menu-grid">
        <view class="menu-item animate-scale-in" v-for="(menu, index) in menuList" :key="index" @click="clickMenu(menu)" :style="{animationDelay: (0.15 + index * 0.02) + 's'}">
          <view class="menu-icon">
            <image class="menu-image" :src="menu.icon" mode="aspectFit"></image>
          </view>
          <text class="menu-text">{{ menu.name }}</text>
        </view>
      </view>
    </view>



    <!-- 新品上市 -->
    <view class="new-products-section animate-slide-up" :style="{animationDelay: '0.15s'}" v-if="programConfig.showNewProducts">
      <view class="section-title">
          <text class="title-text">新品上市</text>
        </view>
      <view class="new-products-container">
        <view v-if="displayedNewProducts.length > 0" class="new-products-list" :class="{animating: isNewProductsAnimating}">
          <view class="new-item" v-for="(item, index) in displayedNewProducts" :key="index" @click="handleProductClick(item)">
            <image :src="item.image" class="new-image" mode="aspectFill"></image>
            <view class="new-badge" :style="{background: `linear-gradient(135deg, ${themeColorStyles.primaryColor}, ${themeColorStyles.primaryColorLight})`, boxShadow: `0 2rpx 8rpx ${themeColorStyles.primaryColorShadow}`}">
              <text class="badge-text">NEW</text>
            </view>
            <view class="new-info">
              <text class="new-title">{{ item.title }}</text>
              <view class="new-price-row">
                <text class="new-price" :style="{color: themeColorStyles.primaryColor}">¥{{ item.price }}</text>
                <text class="new-original-price" v-if="item.originalPrice">¥{{ item.originalPrice }}</text>
              </view>
              <text class="new-sales">新品上市</text>
            </view>
          </view>
        </view>
        <view v-else class="empty-state">
          <text class="empty-text">暂无新品上市</text>
        </view>
      </view>
    </view>

    <!-- 商品推荐 -->
    <view class="recommend-section">
      <!-- 热销商品橱窗 -->
      <view class="hot-showcase animate-slide-up" :style="{animationDelay: '0.2s'}" v-if="programConfig.showHotProducts">
        <view class="section-title">
            <text class="title-text">热销商品</text>
          </view>
        <view class="hot-products-container">
          <view v-if="hotProducts.length > 0" class="hot-products-scroll" ref="hotProductsScroll" :style="{transform: `translateX(${scrollOffset}rpx)`}">
            <view class="hot-item" v-for="(item, index) in hotProducts" :key="index" @click="handleProductClick(item)">
              <image :src="item.image" class="hot-image" mode="aspectFill"></image>
              <view class="hot-info">
                <text class="hot-title">{{ item.title }}</text>
                <view class="hot-price-row">
                  <text class="hot-price" :style="{color: themeColorStyles.primaryColor}">¥{{ item.price }}</text>
                  <text class="hot-original-price">¥{{ item.originalPrice }}</text>
                </view>
                <text class="hot-sales">已售{{ item.sales }}件</text>
              </view>
            </view>
          </view>
          <view v-else class="empty-state">
            <text class="empty-text">该商城没有配置热销商品</text>
          </view>
        </view>
      </view>

      <!-- 推荐商品列表 -->
      <view class="recommend-list animate-slide-up" :style="{animationDelay: '0.25s', '--primary-color': primaryColor, boxShadow: `0 8rpx 32rpx ${themeColorStyles.primaryColorShadow}`, border: `1rpx solid ${themeColorStyles.primaryColorBorder}`}" v-if="programConfig.showRecommendProducts">
        <view class="section-title">
            <text class="title-text">精选推荐</text>
          </view>
        <view class="product-list">
          <view v-if="recommendProductList.length > 0" class="product-items">
            <view class="product-item" v-for="(product, index) in displayedRecommendList" :key="index" @click="clickProduct(product)">
              <image class="product-image" :src="product.image" mode="aspectFill"></image>
              <view class="product-info">
                <text class="product-name">{{ product.name }}</text>
                <view class="product-bottom">
                  <text class="product-price" :style="{color: themeColorStyles.primaryColor}">¥{{ product.price }}</text>
                  <text class="product-sales">已售{{ product.sales }}件</text>
                </view>
              </view>
            </view>
          </view>
          <view v-else class="empty-state">
            <text class="empty-text">该商城没有配置精选推荐商品</text>
          </view>
        </view>
        <!-- 加载更多提示 -->
        <view class="loading-more" v-if="isLoadingMore">
          <text class="loading-text">加载中...</text>
        </view>
        <view class="no-more" v-if="!hasMoreRecommend && displayedRecommendList.length >= 5">
			<text class="no-more-text">已经到底了~</text>
		</view>
      </view>
    </view>
    
    <!-- 底部安全区域，避免内容被TabBar遮挡 -->
    <view class="tabbar-safe-area"></view>
    
    <!-- 自定义TabBar -->
    <CustomTabbar :currentPath="'pages/index'" />
    </view>
  </view>
</template>

<script>
import { listAdvertisement } from '@/api/advertisement'
import { listMobileHotProduct, listMobileRecommendProduct, listMobileNewProduct } from '@/api/product.js'
import { listAnnouncement } from '@/api/announcement'
import { getUserCartList } from '@/api/cart'
import { getPublicProgramConfig } from '@/api/programConfig'
import productCache from '@/utils/productCache.js'
import cartCache from '@/utils/cartCache'
import { API_CONFIG } from '@/api/config.js'
import config from '@/config'
import browseTracker from '@/utils/browseTracker.js'
import { getToken, getUserInfo } from '@/utils/auth'
import { getIndexIconPath, getThemeColorFromGlobal, getThemePrimaryColor } from '@/utils/themeUtils'
import PageLoading from '@/components/PageLoading/index.vue'
import pageLoadingMixin from '@/mixins/pageLoading.js'

export default {
  components: {
    PageLoading
  },
  mixins: [pageLoadingMixin],
  data() {
    return {
      // 小程序配置数据
      programConfig: {
        showBanner: 1,
        showNotice: 1,
        showPopup: 1,
        showNavButtons: 1,
        showNewProducts: 1,
        showHotProducts: 1,
        showRecommendProducts: 1
      },
      // 轮播图数据（仅动态获取）
      bannerList: [],
      // 公告数据（动态加载）
      noticeList: [],
      // 菜单导航数据
      themeColor: '1', // 当前主题色
      baseMenuList: [
        {
          id: 1,
          name: '商品大全',
          iconName: 'buy_shop',
          url: '/pages/shop/index'
        },
        {
          id: 2,
          name: '我的订单',
          iconName: 'my_order',
          url: '/pages/order/index'
        },
        {
          id: 3,
          name: '购物车',
          iconName: 'my_cart',
          url: '/pages/cart/index'
        },
        {
          id: 4,
          name: '我的足迹',
          iconName: 'my_foot',
          url: '/pages/footprint/index'
        },
        {
          id: 5,
          name: '联系客服',
          iconName: 'kefu',
          url: '/pages/contact/index'
        }
      ],
      // 热销商品数据（动态加载）
      hotProducts: [],
      // 新品上市数据（动态加载）
      newProducts: [],
      // 新品分组显示相关
      newProductGroups: [], // 新品分组数据
      currentNewGroup: 0, // 当前显示的组索引
      displayedNewProducts: [], // 当前显示的新品
      newProductsTimer: null, // 新品切换定时器
      isNewProductsAnimating: false, // 是否正在动画中
      // 推荐商品数据（动态加载）
      recommendProductList: [],
      // 分页相关
      currentPage: 1,
      pageSize: 5,
      // 弹窗广告相关
      showPopupAd: false,
      popupAdList: [], // 弹窗广告数据列表
      currentPopupIndex: 0, // 当前显示的弹窗索引
      currentPopupAd: null, // 当前显示的弹窗广告数据
      // 加载状态
      isLoadingMore: false,
      // 热销商品滚动相关
      scrollOffset: 0,
      scrollTimer: null
    }
  },
  async onLoad() {
    // 开始页面加载
    this.startPageLoading()
    
    try {
      // 首次加载时先检测Token状态
      await this.checkTokenStatus()
      
      // 首次加载时执行动画和初始化
      await this.initThemeColor()
      // 标记主题色已加载
      this.markThemeLoaded()
      
      // 加载页面数据
      await Promise.all([
        this.loadProgramConfig(),
        this.loadPopupAdData(),
        this.loadBannerData(),
        this.loadNoticeData(),
        this.loadHotProducts(),
        this.loadNewProducts(),
        this.loadRecommendProducts()
      ])
      
      // 标记数据已加载
      this.markDataLoaded()
    } catch (error) {
      console.error('页面加载失败:', error)
      console.error('页面加载错误详情:', {
        message: error.message,
        stack: error.stack
      })
      // 即使出错也要完成加载，避免页面一直显示加载状态
      this.forceCompletePageLoading()
    }
  },

  onShow() {
    // 页面显示时重置加载状态（用于页面重新显示）
    this.resetPageLoadingForShow()
    
    // 页面显示时不执行动画，只处理必要的数据更新
    // 不调用checkShowPopupAd和startHotProductsScroll，避免重复动画
    
    // 检查是否需要刷新数据（组织切换等情况）
    this.checkAndRefreshData()
    
    // 更新购物车角标
    this.updateCartBadge()
    
    // 恢复浏览时长记录
    browseTracker.resume()
  },

  mounted() {
    // mounted钩子保持为空，避免与onLoad重复执行
  },

  onHide() {
    // 页面隐藏时暂停浏览时长记录
    browseTracker.pause()
  },
  
  onUnload() {
    // 页面卸载时停止浏览时长记录
    browseTracker.stopTracking()
  },
  
  beforeDestroy() {
    if (this.scrollTimer) {
      clearInterval(this.scrollTimer)
    }
    if (this.newProductsTimer) {
      clearInterval(this.newProductsTimer)
    }
    // 确保停止浏览时长记录
    browseTracker.stopTracking()
  },
  computed: {
    // 动态计算菜单列表，包含图标路径
    menuList() {
      return this.baseMenuList.map(item => ({
        ...item,
        icon: getIndexIconPath(this.themeColor, item.iconName)
      }))
    },
    // 当前显示的推荐商品列表
    displayedRecommendList() {
      return this.recommendProductList.slice(0, this.currentPage * this.pageSize)
    },
    // 是否还有更多商品
    hasMoreRecommend() {
      return this.currentPage * this.pageSize < this.recommendProductList.length
    },
    // 动态获取主题色
    primaryColor() {
      return getThemePrimaryColor(this.themeColor)
    },
    // 动态主题色样式（用于小程序环境）
    themeColorStyles() {
      const primaryColor = this.primaryColor
      const rgb = this.hexToRgb(primaryColor)
      if (!rgb) return {}
      
      return {
        primaryColorShadow: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.3)`,
        primaryColorShadowHover: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
        primaryColorBorder: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        primaryColorBgLight: `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
        primaryColorLight: this.lightenColor(primaryColor, 20),
        primaryColor: primaryColor
      }
    }
  },
  methods: {
    // 检测Token状态
    async checkTokenStatus() {
      try {
        const token = uni.getStorageSync('App-Token')
        
        if (!token) {
          // 没有Token，但不立即显示登录提示，让用户可以浏览
          // console.log('没有Token，用户可以继续浏览')
          return
        }
        
        // 检查是否刚刚登录（避免登录后立即弹出登录提示）
        const lastLoginTime = uni.getStorageSync('lastLoginTime')
        const now = Date.now()
        if (lastLoginTime && (now - lastLoginTime) < 5000) {
          // console.log('刚刚登录，跳过Token检测')
          return
        }
        
        // 有Token，使用专门的Token检测接口验证Token是否有效
        const testResponse = await uni.request({
          url: config.baseUrl + '/mobile/token/validate?token=' + encodeURIComponent(token),
          method: 'GET',
          header: {
            'Content-Type': 'application/json'
          }
        })
        
        // console.log('Token检测响应:', testResponse)
        
        // 检查响应状态和数据
        if (testResponse.statusCode === 401 || 
            (testResponse.data && testResponse.data.code === 401)) {
          // Token已过期或无效，显示登录提示
          // console.log('Token已过期，显示登录提示')
          this.showLoginPrompt()
        } else if (testResponse.statusCode === 200 && 
                   testResponse.data && 
                   testResponse.data.code === 200) {
          // Token有效，继续正常流程
          // console.log('Token验证成功，用户ID:', testResponse.data.data)
        } else {
          // 其他错误情况，记录日志但不显示登录提示
          // console.warn('Token检测返回异常状态，但不强制登录:', testResponse)
        }
        
      } catch (error) {
        // console.error('Token检测失败:', error)
        // 检查是否是401错误或者网络请求失败导致的token过期
        if (error.statusCode === 401 || 
            (error.data && error.data.code === 401) ||
            (error[1] && error[1].statusCode === 401) ||
            (error[1] && error[1].data && error[1].data.code === 401)) {
          // console.log('检测到token过期，显示登录提示')
          this.showLoginPrompt()
        } else {
          // 对于网络错误，如果有token但无法验证，也应该提示用户
          // console.warn('Token检测网络异常，但仍提示用户重新登录以确保安全')
          this.showLoginPrompt()
        }
      }
    },
    
    // 显示登录提示弹窗
    showLoginPrompt() {
      // 防止重复弹窗 - 检查全局状态
      const { getLoginModalStatus, setLoginModalStatus } = require('@/utils/loginCheck.js')
      if (getLoginModalStatus()) {
        // console.log('登录弹窗已经显示，跳过重复弹窗')
        return
      }
      
      // 设置弹窗显示状态
      setLoginModalStatus(true)
      
      uni.showModal({
        title: '系统提示',
        content: '登录状态已过期或不存在，您需要重新登录。',
        showCancel: true,
        cancelText: '取消',
        confirmText: '一键登录',
        success: (res) => {
          // 重置弹窗状态
          setLoginModalStatus(false)
          
          if (res.confirm) {
            // 用户点击确认，执行登录逻辑
            try {
              // 清除token
              uni.removeStorageSync('App-Token')
              // 清除用户信息
              uni.removeStorageSync('userId')
              uni.removeStorageSync('storage_data')
              // 清除store中的用户信息
              const app = getApp()
              if (app && app.$store && app.$store.dispatch) {
                app.$store.dispatch('LogOut')
              }
            } catch (error) {
              // console.error('清除登录状态失败:', error)
            }
            
            // 跳转到登录页
            uni.reLaunch({ url: '/pages/login' })
          } else {
            // 用户点击取消，允许继续浏览
            // console.log('用户选择取消登录，继续浏览')
          }
        },
        fail: () => {
          // 弹窗失败时也要重置状态
          setLoginModalStatus(false)
        }
      })
    },
    
    // 初始化主题色
    async initThemeColor() {
      try {
        // 获取主题色配置
        const themeColor = await getThemeColorFromGlobal()
        
        // 判断是否为异步主题色（数字字符串表示需要从服务器获取）
        if (/^\d+$/.test(themeColor)) {
          // 异步获取主题色
          this.themeColor = themeColor
          // console.log('异步获取主题色 - 首页:', themeColor)
        } else {
          // 同步获取主题色（直接使用颜色值）
          this.themeColor = themeColor
          // console.log('同步获取主题色 - 首页:', themeColor)
        }
        this.setThemeColorVariables()
      } catch (error) {
        // console.error('首页主题色初始化失败:', error)
        // 使用默认主题色
        this.themeColor = '1'
        this.setThemeColorVariables()
      }
    },
    
    // 设置主题色CSS变量
    setThemeColorVariables() {
      const primaryColor = getThemePrimaryColor(this.themeColor)
      // 将十六进制颜色转换为RGB值
      const rgb = this.hexToRgb(primaryColor)
      if (rgb) {
        // 在小程序环境中，使用uni.setStorageSync存储主题色变量
        // #ifdef MP
        uni.setStorageSync('themeColorVariables', {
          '--primary-color-shadow': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`,
          '--primary-color-shadow-hover': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`,
          '--primary-color-border': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`,
          '--primary-color-bg-light': `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`
        })
        // #endif
        
        // 在H5环境中，设置CSS变量
        // #ifdef H5
        if (typeof document !== 'undefined' && document.documentElement) {
          const style = document.documentElement.style
          style.setProperty('--primary-color-shadow', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.08)`)
          style.setProperty('--primary-color-shadow-hover', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.15)`)
          style.setProperty('--primary-color-border', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`)
          style.setProperty('--primary-color-bg-light', `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0.1)`)
        }
        // #endif
      }
    },
    
    // 十六进制颜色转RGB
    hexToRgb(hex) {
      const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex)
      return result ? {
        r: parseInt(result[1], 16),
        g: parseInt(result[2], 16),
        b: parseInt(result[3], 16)
      } : null
    },
    
    // 颜色变亮函数
    lightenColor(color, percent) {
      const rgb = this.hexToRgb(color)
      if (!rgb) return color
      
      const r = Math.min(255, Math.floor(rgb.r + (255 - rgb.r) * percent / 100))
      const g = Math.min(255, Math.floor(rgb.g + (255 - rgb.g) * percent / 100))
      const b = Math.min(255, Math.floor(rgb.b + (255 - rgb.b) * percent / 100))
      
      return `#${r.toString(16).padStart(2, '0')}${g.toString(16).padStart(2, '0')}${b.toString(16).padStart(2, '0')}`
    },
    // 点击轮播图
    clickBanner(item) {
      // 如果广告有关联的商品ID，跳转到商品详情页
      if (item.productId || item.product_id) {
        const productId = item.productId || item.product_id
        uni.navigateTo({
          url: `/pages/product/detail?id=${productId}`
        })
      } else if (item.url) {
        // 如果有自定义URL，跳转到指定页面
        uni.navigateTo({
          url: item.url
        })
      } else {
        // 默认提示
        this.$modal.showToast('轮播图功能开发中~')
      }
    },
    // 点击公告
    clickNotice(notice) {
      if (notice.id) {
        // 只传递公告ID到详情页
        uni.navigateTo({
          url: `/pages/announcement/detail?id=${notice.id}`
        })
      } else {
        this.$modal.showToast('公告详情功能开发中~')
      }
    },
    // 点击菜单
    clickMenu(menu) {
      // 根据不同的页面类型选择跳转方式
      if (menu.url === '/pages/shop/index' || menu.url === '/pages/cart/index') {
        // 商品页面和购物车页面是tabBar页面，使用switchTab
        uni.switchTab({
          url: menu.url
        })
      } else {
        // 其他页面使用navigateTo
        uni.navigateTo({
          url: menu.url
        })
      }
    },
    // 点击商品
    clickProduct(product) {
      // 提取原始商品ID，去除_dup_后缀
      const originalId = this.getOriginalProductId(product.id)
      uni.navigateTo({
        url: `/pages/product/detail?id=${originalId}`
      })
    },
    // 点击热销商品
    handleProductClick(product) {
      // 提取原始商品ID，去除_dup_后缀
      const originalId = this.getOriginalProductId(product.id)
      uni.navigateTo({
        url: `/pages/product/detail?id=${originalId}`
      })
    },
    
    // 获取原始商品ID，去除_dup_后缀
    getOriginalProductId(id) {
      if (!id) return 1
      // 如果ID包含_dup_，提取原始ID
      if (typeof id === 'string' && id.includes('_dup_')) {
        return id.split('_dup_')[0]
      }
      return id
    },
    
    // 更新购物车角标
    async updateCartBadge() {
      try {
        const userId = uni.getStorageSync('userId') || 'default'
        let cartCount = 0
        
        // 优先从缓存获取购物车数量
        if (cartCache.isCacheValid(userId)) {
          const cachedData = cartCache.getCartCache(userId)
          if (cachedData && cachedData.length > 0) {
            cartCount = cachedData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
          }
        } else {
          // 缓存无效时从后端获取
          try {
            const response = await getUserCartList()
            if (response.code === 200) {
              const cartData = response.data || []
              cartCount = cartData.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
            }
          } catch (error) {
            const localCart = uni.getStorageSync('cartList') || []
            cartCount = localCart.reduce((total, item) => total + parseInt(item.quantity || 0), 0)
          }
        }
        
        // 更新tabbar角标
        if (cartCount > 0) {
          uni.setTabBarBadge({
            index: 2,
            text: cartCount.toString()
          })
        } else {
          uni.removeTabBarBadge({
            index: 2
          })
        }
      } catch (error) {
        // console.error('更新购物车角标失败:', error)
      }
    },
    // 查看更多热销商品
    viewMoreHot() {
      this.$modal.showToast('热销商品列表功能开发中~')
    },
    // 加载更多推荐商品
    loadMoreRecommend() {
      if (this.hasMoreRecommend && !this.isLoadingMore) {
        this.isLoadingMore = true
        // 立即加载，不延迟
        this.currentPage++
        this.isLoadingMore = false
        this.$modal.showToast(`已加载第${this.currentPage}页商品`)
      }
    },
    // 监听页面滚动
    onReachBottom() {
      this.loadMoreRecommend()
    },
    // 加载弹窗广告数据
    async loadPopupAdData() {
      try {
        const requestParams = {
           adType: '2', // 弹窗类型
           status: '0', // 启用状态
           orgId: '115' // 明确传递组织ID
         }
        
        const response = await listAdvertisement(requestParams)
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          
          // 将后端数据转换为前端需要的格式
          this.popupAdList = response.rows.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.adImage
            
            return {
              id: item.adId,
              image: imageUrl,
              title: item.adTitle || '活动推荐',
              remark: item.remark || '',
              productId: item.productId
            }
          })
          
          // 如果有弹窗广告数据，显示第一个
          if (this.popupAdList.length > 0) {
            this.currentPopupIndex = 0
            this.currentPopupAd = this.popupAdList[0]
            setTimeout(() => {
              this.showPopupAd = true
            }, 1000)
          }
        } else {
          this.popupAdList = []
        }
      } catch (error) {
        // console.error('获取弹窗广告数据失败:', error)
        this.popupAdList = []
      }
    },
    // 关闭弹窗广告
    closePopupAd() {
      this.showPopupAd = false
      
      // 检查是否还有下一个弹窗
      if (this.currentPopupIndex + 1 < this.popupAdList.length) {
        // 显示下一个弹窗
        this.currentPopupIndex++
        this.currentPopupAd = this.popupAdList[this.currentPopupIndex]
        setTimeout(() => {
          this.showPopupAd = true
        }, 500) // 延迟500ms显示下一个弹窗
      } else {
        // 没有更多弹窗了
        this.currentPopupAd = null
        this.currentPopupIndex = 0
      }
    },
    // 处理弹窗广告点击
    handlePopupAction() {
      // 跳转到对应的商品页面
      if (this.currentPopupAd && this.currentPopupAd.productId) {
        uni.navigateTo({
          url: `/pages/product/detail?id=${this.currentPopupAd.productId}`
        })
      }
      this.closePopupAd()
    },
    // 开始热销商品自动滚动
      startHotProductsScroll() {
        if (this.scrollTimer) {
          clearInterval(this.scrollTimer)
        }
        
        // 只有当热销商品数量大于3时才启动滚动
        if (this.hotProducts.length <= 3) {
          return
        }
        
        const itemWidth = 220 // 每个商品项的宽度（200rpx + 20rpx margin）
        // 计算原始商品数量（不包含为滚动效果复制的商品）
        let originalLength = this.hotProducts.length
        if (this.hotProducts.length > 3) {
          // 如果有复制的商品，减去复制的数量
          const duplicateCount = Math.min(2, Math.floor(this.hotProducts.length / 2))
          originalLength = this.hotProducts.length - duplicateCount
        }
        const totalWidth = originalLength * itemWidth
        
        this.scrollTimer = setInterval(() => {
          this.scrollOffset -= 2 // 向左滚动（负值表示向左移动）
          // 当滚动到原始商品列表末尾时，无缝重置到开始位置
          if (Math.abs(this.scrollOffset) >= totalWidth) {
            this.scrollOffset = 0
          }
        }, 50)
      },
    // 页面滚动到底部时触发
    onReachBottom() {
      this.loadMoreRecommend()
    },
    // 加载轮播图广告数据
    async loadBannerData() {
      try {
        const requestParams = {
          adType: '1', // 只获取轮播图类型的广告
          status: '0', // 根据测试结果，状态为0表示启用
          orgId: '115' // 明确传递组织ID
        }
        
        const response = await listAdvertisement(requestParams)
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          
          // 将后端数据转换为前端需要的格式
          this.bannerList = response.rows.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.adImage
            
            return {
              id: item.adId,
              image: imageUrl,
              title: item.adTitle || '默认标题',
              url: item.adUrl || '#',
              productId: item.productId,
              product_id: item.productId  // 兼容两种字段名
            }
          })
        } else {
          // 没有数据时保持空数组
          this.bannerList = []
        }
      } catch (error) {
        // console.error('获取广告数据失败:', error)
        // 如果获取失败，保持空数组
        this.bannerList = []
      }
    },
    
    // 加载公告数据
    async loadNoticeData() {
      // 检查缓存是否有效，缓存键包含orgId
      const cacheKey = `notice_cache_${API_CONFIG.ORG_ID}`
      if (this.isCacheValid(cacheKey)) {
        const cachedData = this.getCacheData(cacheKey)
        if (cachedData && cachedData.length > 0) {
          this.noticeList = cachedData
          return
        }
      }
      
      try {
        const response = await listAnnouncement({
          pageNum: 1,
          pageSize: 10,
          status: '0' // 0表示正常状态
        })
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          
          // 将后端数据转换为前端需要的格式
            const processedNoticeList = response.rows.map(item => {
              const noticeData = {
                id: item.announcementId,
                title: item.title || '系统公告',
                content: item.content || '',
                displayText: `${item.title || '系统公告'}：${item.content || ''}`,
                startTime: item.startTime || new Date().toISOString().replace('T', ' ').substring(0, 19)
              }
              
              // 将每个公告详情单独缓存，缓存键包含orgId
              this.setCacheData(`notice_detail_${item.announcementId}_${API_CONFIG.ORG_ID}`, noticeData)
              
              return noticeData
            })
            
            this.noticeList = processedNoticeList
            // 缓存公告列表
            this.setCacheData(cacheKey, processedNoticeList)
        } else {
          // 没有数据时保持空数组
          this.noticeList = []
        }
      } catch (error) {
        // console.error('获取公告数据失败:', error)
        // 尝试使用缓存数据
        const cachedData = this.getCacheData(cacheKey)
        if (cachedData && cachedData.length > 0) {
          this.noticeList = cachedData
        } else {
          // 如果缓存也没有，保持空数组
          this.noticeList = []
        }
      }
    },
    
    // 设置默认公告数据
    setDefaultNoticeData() {
      // 没有数据时保持空数组
      this.noticeList = []
    },
    
    // 检查缓存是否有效（10分钟有效期）
    isCacheValid(cacheKey) {
      const cacheData = uni.getStorageSync(cacheKey)
      if (!cacheData || !cacheData.timestamp) {
        return false
      }
      const now = Date.now()
      const cacheTime = cacheData.timestamp
      const tenMinutes = 10 * 60 * 1000 // 10分钟的毫秒数
      return (now - cacheTime) < tenMinutes
    },
    
    // 获取缓存数据
    getCacheData(cacheKey) {
      const cacheData = uni.getStorageSync(cacheKey)
      return cacheData ? cacheData.data : null
    },
    
    // 设置缓存数据
    setCacheData(cacheKey, data) {
      const cacheData = {
        data: data,
        timestamp: Date.now()
      }
      uni.setStorageSync(cacheKey, cacheData)
    },
    
    // 统一的商品缓存管理
    getProductCache(type) {
      const orgId = API_CONFIG.ORG_ID
      return productCache.getProductCache(type, orgId)
    },
    
    // 设置商品缓存
    setProductCache(type, data) {
      const orgId = API_CONFIG.ORG_ID
      productCache.setProductCache(type, data, orgId)
    },
    
    // 加载热销商品
    async loadHotProducts() {
      // 检查缓存是否有效
      const cachedData = this.getProductCache('hot')
      if (cachedData && cachedData.length > 0) {
        let processedCachedData = [...cachedData]
        
        // 为了滚动效果，只有当商品数量大于3时才复制前几个商品
        if (processedCachedData.length > 3) {
          const duplicateCount = Math.min(2, processedCachedData.length)
          for (let i = 0; i < duplicateCount; i++) {
            processedCachedData.push({...processedCachedData[i], id: processedCachedData[i].id + '_dup_' + i})
          }
        }
        
        this.hotProducts = processedCachedData
        // 启动滚动
        this.startHotProductsScroll()
        return
      }
      
      try {
        const hotParams = {
          pageNum: 1,
          pageSize: 10
        }
        const response = await listMobileHotProduct(hotParams)
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          
          // 将后端数据转换为前端需要的格式
          let processedHotProducts = response.rows.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.mainImage
            
            return {
              id: item.productId,
              title: item.productName || '商品名称',
              image: imageUrl,
              price: item.price ? item.price.toString() : '0.00',
              originalPrice: item.originalPrice ? item.originalPrice.toString() : (parseFloat(item.price || 0) * 1.3).toFixed(2),
              sales: item.saleCount || 0
            }
          })
          
          // 先缓存原始数据（不包含重复商品）
          this.setProductCache('hot', processedHotProducts)
          
          // 为了滚动效果，只有当商品数量大于3时才复制前几个商品
          if (processedHotProducts.length > 3) {
            const duplicateCount = Math.min(2, processedHotProducts.length)
            for (let i = 0; i < duplicateCount; i++) {
              processedHotProducts.push({...processedHotProducts[i], id: processedHotProducts[i].id + '_dup_' + i})
            }
          }
          
          this.hotProducts = processedHotProducts
          // 重新启动滚动（基于新的商品数量）
          this.startHotProductsScroll()
        } else {
          // 没有数据时保持空数组
          this.hotProducts = []
        }
      } catch (error) {
        // console.error('获取热销商品数据失败:', error)
        // 如果获取失败，尝试使用缓存数据
        const cachedData = this.getProductCache('hot')
        if (cachedData && cachedData.length > 0) {
          let processedCachedData = [...cachedData]
          
          // 为了滚动效果，只有当商品数量大于3时才复制前几个商品
          if (processedCachedData.length > 3) {
            const duplicateCount = Math.min(2, processedCachedData.length)
            for (let i = 0; i < duplicateCount; i++) {
              processedCachedData.push({...processedCachedData[i], id: processedCachedData[i].id + '_dup_' + i})
            }
          }
          
          this.hotProducts = processedCachedData
          // 重新启动滚动
          this.startHotProductsScroll()
        } else {
          // 没有数据时保持空数组
          this.hotProducts = []
        }
      }
    },
    
    // 加载新品上市 - 从热销和推荐商品中筛选
    async loadNewProducts() {
      // 检查缓存是否有效
      const cachedData = this.getProductCache('new')
      if (cachedData && cachedData.length > 0) {
        this.newProducts = cachedData
        this.initNewProductsDisplay()
        return
      }
      
      try {
        // 等待热销商品和推荐商品加载完成，然后从中筛选新品
        await Promise.all([this.loadHotProducts(), this.loadRecommendProducts()])
        
        let allNewProducts = []
        
        // 从已加载的热销商品缓存中筛选新品
        const hotCachedData = this.getProductCache('hot')
        if (hotCachedData && hotCachedData.length > 0) {
          // 需要重新获取原始数据来检查isNew字段
          const hotParams = { pageNum: 1, pageSize: 20 }
          const hotResponse = await listMobileHotProduct(hotParams)
          if (hotResponse.code === 200 && hotResponse.rows) {
            const hotNewProducts = hotResponse.rows.filter(item => item.isNew === '1')
            // console.log('从热销商品中筛选的新品:', hotNewProducts)
            allNewProducts = allNewProducts.concat(hotNewProducts)
          }
        }
        
        // 从已加载的推荐商品缓存中筛选新品
        const recommendCachedData = this.getProductCache('recommend')
        if (recommendCachedData && recommendCachedData.length > 0) {
          // 需要重新获取原始数据来检查isNew字段
          const recommendParams = { pageNum: 1, pageSize: 20 }
          const recommendResponse = await listMobileRecommendProduct(recommendParams)
          if (recommendResponse.code === 200 && recommendResponse.rows) {
            const recommendNewProducts = recommendResponse.rows.filter(item => item.isNew === '1')
            // console.log('从推荐商品中筛选的新品:', recommendNewProducts)
            allNewProducts = allNewProducts.concat(recommendNewProducts)
          }
        }
        
        // 去重（基于productId）
        const uniqueNewProducts = []
        const seenIds = new Set()
        for (const product of allNewProducts) {
          if (!seenIds.has(product.productId)) {
            seenIds.add(product.productId)
            uniqueNewProducts.push(product)
          }
        }
        
        // console.log('去重后的新品数据:', uniqueNewProducts)
        
        if (uniqueNewProducts.length > 0) {
          // 将后端数据转换为前端需要的格式
          let processedNewProducts = uniqueNewProducts.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.mainImage
            
            return {
              id: item.productId,
              title: item.productName || '商品名称',
              image: imageUrl,
              price: item.price ? item.price.toString() : '0.00',
              originalPrice: item.originalPrice ? item.originalPrice.toString() : null,
              sales: item.saleCount || 0
            }
          })
          
          // 缓存原始数据
          this.setProductCache('new', processedNewProducts)
          this.newProducts = processedNewProducts
          // 初始化新品展示
          this.initNewProductsDisplay()
        } else {
          // 没有数据时保持空数组
          this.newProducts = []
          this.displayedNewProducts = []
        }
      } catch (error) {
        // console.error('获取新品失败:', error)
        // 如果获取失败，尝试使用缓存数据
        const cachedData = this.getProductCache('new')
        if (cachedData && cachedData.length > 0) {
          this.newProducts = cachedData
          this.initNewProductsDisplay()
        } else {
          // 没有数据时保持空数组
          this.newProducts = []
          this.displayedNewProducts = []
        }
      }
    },
    

    
    // 初始化新品展示
    initNewProductsDisplay() {
      if (this.newProducts.length === 0) {
        this.displayedNewProducts = []
        this.newProductGroups = []
        return
      }
      
      // 按3个一组分组
      this.newProductGroups = []
      for (let i = 0; i < this.newProducts.length; i += 3) {
        let group = this.newProducts.slice(i, i + 3)
        
        // 如果最后一组不足3个，从前面的商品中补充
        if (group.length < 3 && this.newProducts.length > 3) {
          const needed = 3 - group.length
          const supplementProducts = this.newProducts.slice(0, needed)
          group = group.concat(supplementProducts)
        }
        
        this.newProductGroups.push(group)
      }
      
      // 显示第一组
      this.currentNewGroup = 0
      this.displayedNewProducts = this.newProductGroups[0] || []
      
      // 如果有多组，启动定时切换
      if (this.newProductGroups.length > 1) {
        this.startNewProductsTimer()
      }
    },
    
    // 启动新品定时切换
    startNewProductsTimer() {
      // 清除现有定时器
      if (this.newProductsTimer) {
        clearInterval(this.newProductsTimer)
      }
      
      // 每5秒切换一组
      this.newProductsTimer = setInterval(() => {
        this.switchNewProductsGroup()
      }, 5000)
    },
    
    // 切换新品组
    switchNewProductsGroup() {
      if (this.newProductGroups.length <= 1 || this.isNewProductsAnimating) {
        return
      }
      
      this.isNewProductsAnimating = true
      
      // 下一组索引
      const nextGroup = (this.currentNewGroup + 1) % this.newProductGroups.length
      
      // 切换到新组数据
      this.currentNewGroup = nextGroup
      this.displayedNewProducts = this.newProductGroups[nextGroup]
      
      // 强制重新渲染以触发动画
      this.$nextTick(() => {
        // 等待进场动画完成
        setTimeout(() => {
          this.isNewProductsAnimating = false
        }, 500) // 进场动画时间(0.3s + 0.2s延迟)
      })
    },

    // 加载推荐商品
    async loadRecommendProducts() {
      // 检查缓存是否有效
      const cachedData = this.getProductCache('recommend')
      if (cachedData && cachedData.length > 0) {
        this.recommendProductList = cachedData
        return
      }
      
      try {
        const recommendParams = {
          pageNum: 1,
          pageSize: 20
        }
        const response = await listMobileRecommendProduct(recommendParams)
        
        if (response.code === 200 && response.rows && response.rows.length > 0) {
          
          // 将后端数据转换为前端需要的格式
          let processedRecommendProducts = response.rows.map(item => {
            // 直接使用图片URL，不需要拼接服务器地址（七牛云存储）
            let imageUrl = item.mainImage
            
            // 构建商品描述信息，避免使用富文本字段
            let descriptionParts = []
            if (item.keywords) {
              descriptionParts.push(item.keywords)
            }
            if (item.categoryName) {
              descriptionParts.push(`分类: ${item.categoryName}`)
            }
            if (item.brandName) {
              descriptionParts.push(`品牌: ${item.brandName}`)
            }
            const description = descriptionParts.length > 0 ? descriptionParts.join(' | ') : '精选商品'
            
            return {
              id: item.productId,
              name: item.productName || '商品名称',
              description: description,
              image: imageUrl,
              price: item.price ? item.price.toString() : '0.00',
              sales: item.saleCount || 0,
              keywords: item.keywords || '',
              categoryName: item.categoryName || '',
              brandName: item.brandName || ''
            }
          })
          
          // 如果没有推荐商品，保持空数组
           // processedRecommendProducts 保持原有数据，不添加静态数据
          
          this.recommendProductList = processedRecommendProducts
          // 缓存数据
          this.setProductCache('recommend', processedRecommendProducts)
        } else {
            // 没有数据时保持空数组
            this.recommendProductList = []
          }
      } catch (error) {
        // console.error('获取推荐商品数据失败:', error)
        // 如果获取失败，尝试使用缓存数据
        const cachedData = this.getProductCache('recommend')
        if (cachedData && cachedData.length > 0) {
          this.recommendProductList = cachedData
        } else {
           // 没有数据时保持空数组
           this.recommendProductList = []
         }
      }
    },
    

     
     // 检查并刷新数据
     checkAndRefreshData() {
       // 检查组织是否切换
       const lastOrgId = uni.getStorageSync('last_org_id')
       const currentOrgId = API_CONFIG.ORG_ID
       const orgChanged = lastOrgId && lastOrgId !== currentOrgId
       
       // 检查缓存是否需要刷新
       const lastRefreshTime = uni.getStorageSync('home_last_refresh_time')
       const currentTime = Date.now()
       const refreshInterval = 5 * 60 * 1000 // 5分钟刷新间隔
       
       // 如果组织切换或超过刷新间隔或者没有刷新时间记录，则刷新数据
       if (orgChanged || !lastRefreshTime || (currentTime - lastRefreshTime) > refreshInterval) {
         if (orgChanged) {
           // console.log('组织已切换，重新加载首页数据')
           // 更新记录的组织ID
           uni.setStorageSync('last_org_id', currentOrgId)
         } else {
           // console.log('首页数据需要刷新，重新加载')
         }
         
         this.loadBannerData()
         this.loadNoticeData()
         this.loadHotProducts()
         this.loadRecommendProducts()
         
         // 更新刷新时间
         uni.setStorageSync('home_last_refresh_time', currentTime)
       }
     },
     
     // 开始浏览时长记录
     startBrowseTracking() {
       const token = getToken()
       const userInfo = getUserInfo()
       if (token && userInfo && userInfo.userId) {
         browseTracker.startTracking({
           pageType: 'home',
           pageName: '首页',
           pageUrl: '/pages/index'
         }, userInfo.userId)
       }
     },
     
     // 加载小程序配置
     async loadProgramConfig() {
      try {
        // 使用 App.vue 中的实时获取配置方法
        const app = getApp()
        const config = await app.getProgramConfig()
        
        if (config) {
          this.programConfig = {
            showBanner: config.showBanner !== undefined ? config.showBanner : 1,
            showNotice: config.showNotice !== undefined ? config.showNotice : 1,
            showPopup: config.showPopup !== undefined ? config.showPopup : 1,
            showNavButtons: config.showNavButtons !== undefined ? config.showNavButtons : 1,
            showNewProducts: config.showNewProducts !== undefined ? config.showNewProducts : 1,
            showHotProducts: config.showHotProducts !== undefined ? config.showHotProducts : 1,
            showRecommendProducts: config.showRecommendProducts !== undefined ? config.showRecommendProducts : 1
          }
        }
      } catch (error) {
        // console.error('获取小程序配置失败:', error)
        // 使用默认配置
        this.programConfig = {
          showBanner: 1,
          showNotice: 1,
          showPopup: 1,
          showNavButtons: 1,
           showNewProducts: 1,
           showHotProducts: 1,
           showRecommendProducts: 1
         }
       }
     }
   }
  }
</script>

<style lang="scss" scoped>
.home-container {
  background: #FFFFFF;
  min-height: 100vh;
  position: relative;
  padding-top: 0;
  margin-top: 0;
  padding-bottom: 160rpx; /* 增加底部间距避免TabBar遮挡 */
}

/* 弹窗广告样式 */
.popup-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  animation: fadeIn 0.3s ease-out;
}

.popup-content {
  width: 600rpx;
  background: #fff;
  border-radius: 30rpx;
  overflow: hidden;
  position: relative;
  box-shadow: 0 20rpx 60rpx rgba(30, 58, 138, 0.3);
  animation: popupSlideIn 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.popup-close {
  position: absolute;
  top: 20rpx;
  right: 20rpx;
  width: 60rpx;
  height: 60rpx;
  background: rgba(0, 0, 0, 0.5);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
  
  .close-icon {
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
  }
}

.popup-image {
  width: 100%;
  height: 400rpx;
}

.popup-info {
  padding: 40rpx;
  text-align: center;
  
  .popup-title {
    display: block;
    font-size: 36rpx;
    font-weight: 600;
    margin-bottom: 15rpx;
  }
  
  .popup-subtitle {
    display: block;
    font-size: 28rpx;
    color: #475569;
    margin-bottom: 30rpx;
  }
  
  .popup-button {
    padding: 25rpx 60rpx;
    border-radius: 50rpx;
    background: #4A90E2;
    
    .button-text {
      color: #fff;
      font-size: 30rpx;
      font-weight: 600;
    }
  }
}

/* 动画定义 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes popupSlideIn {
  from {
    opacity: 0;
    transform: scale(0.8) translateY(-50rpx);
  }
  to {
    opacity: 1;
    transform: scale(1) translateY(0);
  }
}

@keyframes fadeInUp {
  from {
    opacity: 0;
    transform: translateY(60rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes slideInLeft {
  from {
    opacity: 0;
    transform: translateX(-60rpx);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
}

@keyframes scaleIn {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes bounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10rpx);
  }
  60% {
    transform: translateY(-5rpx);
  }
}

@keyframes float {
  0%, 100% {
    transform: translateY(0);
  }
  50% {
    transform: translateY(-8rpx);
  }
}

@keyframes glow {
  0%, 100% {
    text-shadow: 0 0 10rpx rgba(135, 206, 250, 0.5);
  }
  50% {
    text-shadow: 0 0 20rpx rgba(135, 206, 250, 0.8), 0 0 30rpx rgba(135, 206, 250, 0.6);
  }
}

@keyframes bounceIn {
  0% {
    opacity: 0;
    transform: scale(0.3);
  }
  50% {
    opacity: 1;
    transform: scale(1.05);
  }
  70% {
    transform: scale(0.9);
  }
  100% {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 动画类 */
.animate-fade-in {
  animation: fadeInUp 0.4s ease-out forwards;
  opacity: 0;
}

.animate-slide-up {
  animation: fadeInUp 0.4s ease-out forwards;
  opacity: 0;
}

.animate-slide-in-left {
  animation: slideInLeft 0.3s ease-out forwards;
  opacity: 0;
}

.animate-scale-in {
  animation: scaleIn 0.3s ease-out forwards;
  opacity: 0;
}

.animate-bounce {
  animation: bounce 1.5s infinite;
}

.animate-float {
  animation: float 2s ease-in-out infinite;
}

.animate-glow {
  animation: glow 1.5s ease-in-out infinite;
}

.animate-bounce-in {
  animation: bounceIn 0.4s ease-out forwards;
  opacity: 0;
}

/* 轮播图样式 */
.banner-section {
  padding-top: 20rpx;
  
  .banner-container {
    margin: 0 32rpx 24rpx;
    border-radius: 24rpx;
    overflow: hidden;
    box-shadow: 0 8rpx 32rpx var(--primary-color-shadow, rgba(74, 144, 226, 0.08));
    border: none;
    
    .banner-swiper {
      height: 400rpx;
      
      .banner-image {
        width: 100%;
        height: 100%;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        &:active {
          transform: scale(0.98);
        }
      }
    }
  }
}

/* 公告样式 */
.notice-section {
  display: flex;
  align-items: center;
  background: #FFFFFF;
  padding: 24rpx 32rpx;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx var(--primary-color-shadow, rgba(74, 144, 226, 0.08));
  border: 1rpx solid var(--primary-color-border, rgba(74, 144, 226, 0.1));
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: translateY(-4rpx);
    box-shadow: 0 12rpx 48rpx var(--primary-color-shadow-hover, rgba(74, 144, 226, 0.15));
  }
  
  .notice-emoji {
    margin-right: 24rpx;
    font-size: 28rpx;
  }
  
  .notice-swiper {
    flex: 1;
    height: 60rpx;
    
    .notice-text {
      font-size: 26rpx;
      color: #1A1A1A;
      line-height: 60rpx;
      transition: color 0.3s ease;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      max-width: 100%;
    }
  }
}

/* 菜单导航样式 */
.menu-section {
  --primary-color: #4A90E2;
  background: #FFFFFF;
  padding: 40rpx 32rpx;
  margin: 24rpx 32rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx var(--primary-color-shadow, rgba(74, 144, 226, 0.08));
  border: 1rpx solid var(--primary-color-border, rgba(74, 144, 226, 0.1));
  
  .menu-grid {
    display: flex;
    justify-content: space-between;
    
    .menu-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      width: 120rpx;
      transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
      
      &:active {
        transform: scale(0.9);
      }
      
      .menu-icon {
        width: 80rpx;
        height: 80rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 16rpx;
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        
        .menu-image {
          width: 48rpx;
          height: 48rpx;
          transition: transform 0.3s ease;
        }
        
        &:active .menu-image {
          transform: scale(1.1);
        }
      }
      
      .menu-text {
        font-size: 24rpx;
        color: #1A1A1A;
        font-weight: 500;
        transition: all 0.3s ease;
      }
      
      &:active .menu-text {
        color: var(--primary-color, #4A90E2);
        transform: scale(0.95);
      }
    }
  }
}

/* 推荐区域样式 */
.recommend-section {
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 32rpx 28rpx;
    background: #FFFFFF;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 32rpx;
      right: 32rpx;
      height: 1rpx;
      background: var(--primary-color-border, rgba(74, 144, 226, 0.1));
    }
    
    .title-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #1A1A1A;
      position: relative;
    }
    
    .more-text {
      font-size: 26rpx;
      color: var(--primary-color, #4A90E2);
      transition: all 0.3s ease;
      padding: 10rpx 20rpx;
      border-radius: 20rpx;
      
      &:active {
        background: var(--primary-color-bg-light, rgba(74, 144, 226, 0.1));
        color: var(--primary-color, #4A90E2);
        transform: scale(0.95);
      }
    }
  }
}

/* 热销商品橱窗样式 */
.hot-showcase {
  --primary-color: #4A90E2;
  background: #FFFFFF;
  margin: 32rpx 32rpx 24rpx;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx var(--primary-color-shadow, rgba(74, 144, 226, 0.08));
  border: 1rpx solid var(--primary-color-border, rgba(74, 144, 226, 0.1));
  overflow: hidden;
  
  .hot-products-container {
    padding: 25rpx 30rpx 35rpx;
    overflow: hidden;
    width: 100%;
    margin: 0 15rpx;
    
    .hot-products-scroll {
        display: flex;
        white-space: nowrap;
        transition: none;
        will-change: transform;
        width: calc(220rpx * 6);
      
      .hot-item {
        display: inline-block;
        width: 200rpx;
        margin-right: 20rpx;
        flex-shrink: 0;
        background: #fff;
        border-radius: 16rpx;
        box-shadow: 0 4rpx 16rpx var(--primary-color-shadow, rgba(74, 144, 226, 0.08));
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 1rpx solid var(--primary-color-border, rgba(74, 144, 226, 0.1));
        
        &:active {
          transform: scale(0.95);
          box-shadow: 0 8rpx 24rpx var(--primary-color-shadow-hover, rgba(74, 144, 226, 0.15));
        }
        
        .hot-image {
          width: 100%;
          height: 160rpx;
          border-radius: 16rpx 16rpx 0 0;
          background: transparent;
        }
        
        .hot-info {
          padding: 15rpx;
          
          .hot-title {
            font-size: 24rpx;
            color: #1A1A1A;
            font-weight: 500;
            margin-bottom: 8rpx;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
          
          .hot-price-row {
            display: flex;
            align-items: center;
            margin-bottom: 5rpx;
            
            .hot-price {
              font-size: 26rpx;
              font-weight: bold;
              margin-right: 10rpx;
            }
            
            .hot-original-price {
              font-size: 20rpx;
              color: #8A8A8A;
              text-decoration: line-through;
            }
          }
          
          .hot-sales {
            font-size: 20rpx;
            color: #8A8A8A;
            display: block;
          }
        }
      }
    }
  }
}

/* 新品上市样式 */
.new-products-section {
  --primary-color: #4A90E2;
  background: #FFFFFF;
  margin: 24rpx 32rpx;
  border-radius: 24rpx;
  box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.08);
  border: 1rpx solid rgba(74, 144, 226, 0.1);
  overflow: hidden;
  
  .section-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 40rpx 32rpx 28rpx;
    background: #FFFFFF;
    position: relative;
    
    &::after {
      content: '';
      position: absolute;
      bottom: 0;
      left: 32rpx;
      right: 32rpx;
      height: 1rpx;
      background: rgba(74, 144, 226, 0.1);
    }
    
    .title-text {
      font-size: 32rpx;
      font-weight: 600;
      color: #1A1A1A;
      position: relative;
    }
  }
  
  .new-products-container {
    padding: 25rpx 32rpx 35rpx;
    overflow: hidden;
    width: 100%;
    
    .new-products-list {
         display: flex;
         flex-direction: column;
         gap: 20rpx;
         
         .new-item {
           opacity: 1;
           transform: translateX(0);
           transition: all 0.3s ease;
         }
         
         &.animating .new-item {
           opacity: 0;
           transform: translateX(100%);
           animation: slideInRight 0.3s ease-out forwards;
         }
         
         &.animating .new-item:nth-child(1) {
           animation-delay: 0s;
         }
         
         &.animating .new-item:nth-child(2) {
           animation-delay: 0.1s;
         }
         
         &.animating .new-item:nth-child(3) {
           animation-delay: 0.2s;
         }
      
      .new-item {
          width: 100%;
          background: #fff;
          border-radius: 16rpx;
          box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.08);
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          border: 1rpx solid rgba(74, 144, 226, 0.1);
          position: relative;
          display: flex;
          align-items: center;
          padding: 20rpx;
          opacity: 1;
          transform: translateX(0);
          
          &:active {
            transform: scale(0.95);
            box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.15);
          }
        
        .new-image {
          width: 120rpx;
          height: 120rpx;
          border-radius: 12rpx;
          background: transparent;
          margin-right: 20rpx;
          flex-shrink: 0;
        }
        
        .new-badge {
          position: absolute;
          top: 8rpx;
          right: 8rpx;
          color: #FFFFFF;
          padding: 4rpx 8rpx;
          border-radius: 8rpx;
          font-size: 18rpx;
          font-weight: bold;
          
          .badge-text {
            font-size: 18rpx;
            font-weight: bold;
          }
        }
        
        .new-info {
          flex: 1;
          display: flex;
          flex-direction: column;
          justify-content: center;
          padding-right: 60rpx;
          
          .new-title {
            font-size: 24rpx;
            color: #1A1A1A;
            font-weight: 500;
            margin-bottom: 8rpx;
            display: -webkit-box;
            -webkit-box-orient: vertical;
            -webkit-line-clamp: 1;
            overflow: hidden;
            text-overflow: ellipsis;
            line-height: 1.4;
            max-height: 1.4em;
            width: 100%;
          }
          
          .new-price-row {
            display: flex;
            align-items: center;
            margin-bottom: 5rpx;
            
            .new-price {
              font-size: 26rpx;
              font-weight: bold;
              margin-right: 10rpx;
            }
            
            .new-original-price {
              font-size: 20rpx;
              color: #8A8A8A;
              text-decoration: line-through;
            }
          }
          
          .new-description {
            font-size: 20rpx;
            color: #8A8A8A;
            display: block;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
    }
  }
}


/* 推荐商品列表样式 */
.recommend-list {
  --primary-color: #4A90E2;
  background: #FFFFFF;
  margin: 32rpx 32rpx 0;
  padding-bottom: 24rpx;
  border-radius: 24rpx 24rpx 0 0;
  box-shadow: 0 8rpx 32rpx rgba(74, 144, 226, 0.08);
  border: 1rpx solid rgba(74, 144, 226, 0.1);
  overflow: hidden;
  
  .product-list {
    padding: 20rpx 32rpx;
    
    .product-item {
      display: flex;
      padding: 28rpx 0;
      border-bottom: 1rpx solid rgba(74, 144, 226, 0.1);
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      position: relative;
      
      &:last-child {
        border-bottom: none;
      }
      
      &:active {
        transform: scale(0.98);
        background: rgba(74, 144, 226, 0.02);
      }
      
      .product-image {
        width: 180rpx;
        height: 180rpx;
        border-radius: 16rpx;
        margin-right: 32rpx;
        box-shadow: 0 4rpx 16rpx rgba(74, 144, 226, 0.08);
        transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
        border: 1rpx solid rgba(74, 144, 226, 0.1);
      }
      
      &:active .product-image {
        transform: scale(1.02);
        box-shadow: 0 8rpx 24rpx rgba(74, 144, 226, 0.15);
      }
      
      .product-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
        
        .product-name {
          font-size: 30rpx;
          color: #1A1A1A;
          font-weight: 600;
          margin-bottom: 12rpx;
          transition: all 0.3s ease;
        }
        

        
        .product-bottom {
          display: flex;
          justify-content: space-between;
          align-items: center;
          
          .product-price {
            font-size: 32rpx;
            font-weight: 600;
            transition: all 0.3s ease;
          }
          
          .product-sales {
            font-size: 24rpx;
            color: #8A8A8A;
            transition: color 0.3s ease;
          }
        }
      }
      
      &:active .product-info {
        .product-name {
          color: var(--primary-color, #4A90E2);
          transform: translateX(5rpx);
        }
        

        
        .product-bottom {
            .product-price {
              transform: scale(1.05);
            }
          
          .product-sales {
            color: var(--primary-color, #4A90E2);
          }
        }
      }
    }
  }
  
  /* 加载状态提示 */
  .loading-more {
    padding: 20rpx 0;
    text-align: center;
    border-top: 1rpx solid rgba(74, 144, 226, 0.1);
    
    .loading-text {
      font-size: 24rpx;
      color: var(--primary-color, #4A90E2);
    }
  }
  
  .no-more {
    padding: 24rpx;
    text-align: center;
    border-top: 1rpx solid rgba(74, 144, 226, 0.1);
    
    .no-more-text {
      font-size: 24rpx;
      color: #8A8A8A;
    }
  }
  
  .empty-state {
    padding: 80rpx 40rpx;
    text-align: center;
    
    .empty-text {
      font-size: 28rpx;
      color: #999999;
      line-height: 1.5;
    }
  }
  
  /* TabBar安全区域 */
  .tabbar-safe-area {
    height: 200rpx;
    padding-bottom: constant(safe-area-inset-bottom);
    padding-bottom: env(safe-area-inset-bottom);
  }
  
  /* 新品切换动画 */
  @keyframes slideInRight {
    0% {
      opacity: 0;
      transform: translateX(100%);
    }
    100% {
      opacity: 1;
      transform: translateX(0);
    }
  }
  
  @keyframes slideOutLeft {
    0% {
      opacity: 1;
      transform: translateX(0);
    }
    100% {
      opacity: 0;
      transform: translateX(-100%);
    }
  }
}
</style>
